package com.lkb.administrator.okuweather;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lkb.administrator.okuweather.gson.Forecast;
import com.lkb.administrator.okuweather.gson.Weather;
import com.lkb.administrator.okuweather.service.MyService;
import com.lkb.administrator.okuweather.util.HttpUtil;
import com.lkb.administrator.okuweather.util.UtilIty;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;
    private Button navBtn;
    public SwipeRefreshLayout swirefresh;
    private String weathreId;
    private ImageView imageView;
    private ScrollView weatherLaout;
    private TextView titlCity;
    private TextView titleUpdateTime;
    private TextView degreeText;
    private TextView weatherInfoText;
    private LinearLayout forcaseLayout;
    private TextView aqiText;
    private TextView pm25Text;
    private TextView comforText;
    private TextView carWahgText;
    private TextView sportText;


    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);




        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        setContentView(R.layout.activity_weather);
        //初始化控件
        navBtn = (Button) findViewById(R.id.nav_button);
        drawerLayout = (DrawerLayout) findViewById(R.id.draw_layout);
       swirefresh = (SwipeRefreshLayout) findViewById(R.id.swip_refresh);
        swirefresh.setColorSchemeColors(R.color.colorPrimary);
        imageView = (ImageView) findViewById(R.id.big_back);
        weatherLaout = (ScrollView) findViewById(R.id.weatheer_layout);
        titlCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.titile_updatetime);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weaer_info_text);
        forcaseLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        comforText = (TextView) findViewById(R.id.comf_text);
        carWahgText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String weathing = preferences.getString("weather",null);
        if (weathing != null) {
            Weather weather = UtilIty.handleResponse(weathing);
            weathreId = weather.basic.weatherId;
            showWeatherInfo(weather);


        }else  {

            weathreId = getIntent().getStringExtra("weather_id");

            weatherLaout.setVisibility(View.INVISIBLE);

            requerst(weathreId);

        }

        swirefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requerst(weathreId);
            }
        });


        navBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                drawerLayout.openDrawer(GravityCompat.START);

            }
        });

        String bigPic = preferences.getString("bing_pic",null);
        if (bigPic != null) {

            Glide.with(this).load(bigPic).into(imageView);

        }else  {

            loadImage();
        }



    }



    private void loadImage(){

        String address = "http://guolin.tech/api/bing_pic";
        HttpUtil.SendOkHttpRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final  String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                editor.putString("bing_pic",bingPic);

                editor.apply();



                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(imageView);
                    }
                });

            }
        });






    }

    public   void requerst(final  String weahterID){

        String urlStr = "http://guolin.tech/api/weather?cityid="+ weahterID +"&key=bc0418b57b2d4918819d3974ac1285d9";
        HttpUtil.SendOkHttpRequest(urlStr, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this,"获取天气失败",Toast.LENGTH_SHORT).show();
                        swirefresh.setRefreshing(false);
                    }
                });



            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final  String responseText = response.body().string();
                final  Weather weather = UtilIty.handleResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (weather != null && "ok".equals(weather.status)){
                            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                            editor.putString("weather",responseText);
                            editor.apply();
                            weathreId = weather.basic.weatherId;
                            showWeatherInfo(weather);








                        }else  {



                            Toast.makeText(WeatherActivity.this,"获取天气失败",Toast.LENGTH_SHORT).show();

                        }

                        swirefresh.setRefreshing(false);




                    }
                });










            }
        });





        loadImage();
    }

    private  void showWeatherInfo(Weather weather) {
        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        String degree = weather.now.temperature +"℃";
        String weathInfo = weather.now.more.info;
        titlCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degree);

        weatherInfoText.setText(weathInfo);

        forcaseLayout.removeAllViews();

        for (Forecast temp : weather.forecastList){
            View view = LayoutInflater.from(this).inflate(R.layout.fore_item,forcaseLayout,false);
            TextView dateText = (TextView) view.findViewById(R.id.date_text);
            TextView infoText = (TextView) view.findViewById(R.id.info_text);
            TextView maxText = (TextView) view.findViewById(R.id.max_text);
            TextView minText = (TextView) view.findViewById(R.id.min_text);

            dateText.setText(temp.date);
            infoText.setText(temp.more.info);
            maxText.setText(temp.temperature.max);
            minText.setText(temp.temperature.min);

            forcaseLayout.addView(view);


        }


        if (weather.aqi != null) {

            aqiText.setText(weather.aqi.city.aqi);
            pm25Text.setText(weather.aqi.city.pm25);

        }

        String comfor = "舒适度: " + weather.suggestion.comfort.info;
        String carWash = "洗车指数: " + weather.suggestion.carwash.info;
        String sport = "运动建议: " + weather.suggestion.sport.info;

        comforText.setText(comfor);
        carWahgText.setText(carWash);
        sportText.setText(sport);

        weatherLaout.setVisibility(View.VISIBLE);

        Intent intent = new Intent(this, MyService.class);


        startService(intent);






    }
}
